package com.leetcode.offer.chapter5;

import com.leetcode.basic.TreeNode;

/**
 * @author Dennis Li
 * @date 2020/7/17 20:30
 */
public class BSTLowestCommonAncestor_68 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        // 要活用BST的性质。根节点值比p q都大，那么公共结点一定在左子树
        if (root.val < p.val && root.val < q.val)
            return lowestCommonAncestor(root.right, p, q);
        // 要活用BST的性质。根节点值比p q都小，那么公共结点一定在右子树
        if (root.val > p.val && root.val > q.val)
            return lowestCommonAncestor(root.left, p, q);
        // 否则返回根节点
        return root;
    }
}
